package com.example.controller;

import com.example.common.Result;
import com.example.entity.Review;
import com.example.entity.User;
import com.example.service.ReviewService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 评价控制器
 * @author System
 * @date 2024
 */
@Controller
@RequestMapping("/review")
public class ReviewController {
    
    private static final Logger logger = LoggerFactory.getLogger(ReviewController.class);
    
    @Autowired
    private ReviewService reviewService;
    
    /**
     * 添加评价
     */
    @PostMapping("/add")
    @ResponseBody
    public Result addReview(@RequestBody Review review, HttpSession session) {
        try {
            User currentUser = (User) session.getAttribute("user");
            if (currentUser == null) {
                return Result.unauthorized("请先登录");
            }
            
            // 参数验证
            if (review == null || review.getProductId() == null || 
                review.getRating() == null || review.getContent() == null) {
                return Result.badRequest("参数不完整");
            }
            
            // 检查用户是否已经评价过该商品
            if (reviewService.hasUserReviewedProduct(currentUser.getId(), review.getProductId())) {
                return Result.error("您已经评价过该商品");
            }
            
            // 设置用户ID
            review.setUserId(currentUser.getId());
            
            boolean success = reviewService.addReview(review);
            if (success) {
                logger.info("添加评价成功: userId={}, productId={}", currentUser.getId(), review.getProductId());
                return Result.success("评价成功");
            } else {
                return Result.error("评价失败");
            }
        } catch (Exception e) {
            logger.error("添加评价异常", e);
            return Result.error("系统异常");
        }
    }
    
    /**
     * 根据ID查询评价
     */
    @GetMapping("/{id}")
    @ResponseBody
    public Result getReviewById(@PathVariable Long id) {
        try {
            Review review = reviewService.getReviewById(id);
            if (review != null) {
                return Result.success("查询成功", review);
            } else {
                return Result.notFound("评价不存在");
            }
        } catch (Exception e) {
            logger.error("查询评价异常: id={}", id, e);
            return Result.error("系统异常");
        }
    }
    
    /**
     * 查询所有评价（管理员功能）
     */
    @GetMapping("/list")
    @ResponseBody
    public Result getAllReviews(HttpSession session) {
        try {
            User currentUser = (User) session.getAttribute("user");
            if (currentUser == null) {
                return Result.unauthorized("请先登录");
            }
            
            // 简单的权限检查（这里假设用户名为admin的是管理员）
            if (!"admin".equals(currentUser.getUsername())) {
                return Result.forbidden("权限不足");
            }
            
            List<Review> reviews = reviewService.getAllReviews();
            return Result.success("查询成功", reviews);
        } catch (Exception e) {
            logger.error("查询所有评价异常", e);
            return Result.error("系统异常");
        }
    }
    
    /**
     * 根据商品ID查询评价
     */
    @GetMapping("/product/{productId}")
    @ResponseBody
    public Result getReviewsByProductId(@PathVariable Long productId,
                                       @RequestParam(defaultValue = "1") int page,
                                       @RequestParam(defaultValue = "10") int size,
                                       @RequestParam(required = false) String sort) {
        try {
            List<Review> reviews;
            
            if (sort != null && !sort.isEmpty()) {
                // 带排序的查询
                reviews = reviewService.getReviewsByProductIdWithSort(productId, sort);
            } else {
                // 分页查询
                reviews = reviewService.getReviewsByProductIdWithPage(productId, page, size);
            }
            
            // 获取统计信息
            int total = reviewService.getReviewCountByProductId(productId);
            Double avgRating = reviewService.getAverageRatingByProductId(productId);
            Map<Integer, Integer> ratingStats = reviewService.getRatingStatsByProductId(productId);
            
            // 构建结果
            Map<String, Object> result = new HashMap<>();
            result.put("list", reviews);
            result.put("total", total);
            result.put("averageRating", avgRating);
            result.put("ratingStats", ratingStats);
            
            if (sort == null || sort.isEmpty()) {
                result.put("page", page);
                result.put("size", size);
                result.put("pages", (total + size - 1) / size);
            }
            
            return Result.success("查询成功", result);
        } catch (Exception e) {
            logger.error("根据商品ID查询评价异常: productId={}", productId, e);
            return Result.error("系统异常");
        }
    }
    
    /**
     * 根据用户ID查询评价
     */
    @GetMapping("/user/{userId}")
    @ResponseBody
    public Result getReviewsByUserId(@PathVariable Long userId, HttpSession session) {
        try {
            User currentUser = (User) session.getAttribute("user");
            if (currentUser == null) {
                return Result.unauthorized("请先登录");
            }
            
            // 只能查看自己的评价或管理员可以查看所有
            if (!currentUser.getId().equals(userId) && !"admin".equals(currentUser.getUsername())) {
                return Result.forbidden("权限不足");
            }
            
            List<Review> reviews = reviewService.getReviewsByUserId(userId);
            int total = reviewService.getReviewCountByUserId(userId);
            
            Map<String, Object> result = new HashMap<>();
            result.put("list", reviews);
            result.put("total", total);
            
            return Result.success("查询成功", result);
        } catch (Exception e) {
            logger.error("根据用户ID查询评价异常: userId={}", userId, e);
            return Result.error("系统异常");
        }
    }
    
    /**
     * 分页查询评价（管理员功能）
     */
    @GetMapping("/page")
    @ResponseBody
    public Result getReviewsByPage(@RequestParam(defaultValue = "1") int page,
                                  @RequestParam(defaultValue = "10") int size,
                                  HttpSession session) {
        try {
            User currentUser = (User) session.getAttribute("user");
            if (currentUser == null) {
                return Result.unauthorized("请先登录");
            }
            
            // 简单的权限检查
            if (!"admin".equals(currentUser.getUsername())) {
                return Result.forbidden("权限不足");
            }
            
            List<Review> reviews = reviewService.getReviewsByPage(page, size);
            int total = reviewService.getReviewCount();
            
            // 构建分页结果
            Map<String, Object> result = new HashMap<>();
            result.put("list", reviews);
            result.put("total", total);
            result.put("page", page);
            result.put("size", size);
            result.put("pages", (total + size - 1) / size);
            
            return Result.success("查询成功", result);
        } catch (Exception e) {
            logger.error("分页查询评价异常: page={}, size={}", page, size, e);
            return Result.error("系统异常");
        }
    }
    
    /**
     * 根据评分查询评价
     */
    @GetMapping("/rating/{rating}")
    @ResponseBody
    public Result getReviewsByRating(@PathVariable Integer rating) {
        try {
            List<Review> reviews = reviewService.getReviewsByRating(rating);
            return Result.success("查询成功", reviews);
        } catch (Exception e) {
            logger.error("根据评分查询评价异常: rating={}", rating, e);
            return Result.error("系统异常");
        }
    }
        /**
     * 根据评分查询评价
     */
    @GetMapping("/count")
    @ResponseBody
    public Result count() {
        try {
            return Result.success( reviewService.getReviewCount());
        } catch (Exception e) {
            return Result.error("系统异常");
        }
    }

    /**
     * 更新评价
     */
    @PutMapping("/update")
    @ResponseBody
    public Result updateReview(@RequestBody Review review, HttpSession session) {
        try {
            User currentUser = (User) session.getAttribute("user");
            if (currentUser == null) {
                return Result.unauthorized("请先登录");
            }
            
            if (review == null || review.getId() == null) {
                return Result.badRequest("参数不完整");
            }
            
            // 检查评价是否存在且属于当前用户
            Review existingReview = reviewService.getReviewById(review.getId());
            if (existingReview == null) {
                return Result.notFound("评价不存在");
            }
            
            if (!currentUser.getId().equals(existingReview.getUserId()) && 
                !"admin".equals(currentUser.getUsername())) {
                return Result.forbidden("只能修改自己的评价");
            }
            
            boolean success = reviewService.updateReview(review);
            if (success) {
                return Result.success("更新成功");
            } else {
                return Result.error("更新失败");
            }
        } catch (Exception e) {
            logger.error("更新评价异常", e);
            return Result.error("系统异常");
        }
    }
    
    /**
     * 审核评价（管理员功能）
     */
    @PutMapping("/audit")
    @ResponseBody
    public Result auditReview(@RequestBody Map<String, Object> params, HttpSession session) {
        try {
            User currentUser = (User) session.getAttribute("user");
            if (currentUser == null) {
                return Result.unauthorized("请先登录");
            }
            
            // 简单的权限检查
            if (!"admin".equals(currentUser.getUsername())) {
                return Result.forbidden("权限不足");
            }
            
            Long reviewId = Long.valueOf(params.get("reviewId").toString());
            Integer status = Integer.valueOf(params.get("status").toString());
            
            boolean success = reviewService.auditReview(reviewId, status);
            if (success) {
                return Result.success("审核成功");
            } else {
                return Result.error("审核失败");
            }
        } catch (Exception e) {
            logger.error("审核评价异常", e);
            return Result.error("系统异常");
        }
    }
    
    /**
     * 获取待审核评价列表（管理员功能）
     */
    @GetMapping("/pending")
    @ResponseBody
    public Result getPendingReviews(HttpSession session) {
        try {
            User currentUser = (User) session.getAttribute("user");
            if (currentUser == null) {
                return Result.unauthorized("请先登录");
            }
            
            // 简单的权限检查
            if (!"admin".equals(currentUser.getUsername())) {
                return Result.forbidden("权限不足");
            }
            
            List<Review> reviews = reviewService.getPendingReviews();
            return Result.success("查询成功", reviews);
        } catch (Exception e) {
            logger.error("获取待审核评价异常", e);
            return Result.error("系统异常");
        }
    }
    
    /**
     * 删除评价
     */
    @DeleteMapping("/{id}")
    @ResponseBody
    public Result deleteReview(@PathVariable Long id, HttpSession session) {
        try {
            User currentUser = (User) session.getAttribute("user");
            if (currentUser == null) {
                return Result.unauthorized("请先登录");
            }
            
            // 检查评价是否存在且属于当前用户
            Review existingReview = reviewService.getReviewById(id);
            if (existingReview == null) {
                return Result.notFound("评价不存在");
            }
            
            if (!currentUser.getId().equals(existingReview.getUserId()) && 
                !"admin".equals(currentUser.getUsername())) {
                return Result.forbidden("只能删除自己的评价");
            }
            
            boolean success = reviewService.deleteReview(id);
            if (success) {
                return Result.success("删除成功");
            } else {
                return Result.error("删除失败");
            }
        } catch (Exception e) {
            logger.error("删除评价异常: id={}", id, e);
            return Result.error("系统异常");
        }
    }
    
    /**
     * 批量删除评价（管理员功能）
     */
    @DeleteMapping("/batch")
    @ResponseBody
    public Result deleteReviews(@RequestBody List<Long> ids, HttpSession session) {
        try {
            User currentUser = (User) session.getAttribute("user");
            if (currentUser == null) {
                return Result.unauthorized("请先登录");
            }
            
            // 简单的权限检查
            if (!"admin".equals(currentUser.getUsername())) {
                return Result.forbidden("权限不足");
            }
            
            if (ids == null || ids.isEmpty()) {
                return Result.badRequest("请选择要删除的评价");
            }
            
            boolean success = reviewService.deleteReviews(ids);
            if (success) {
                return Result.success("批量删除成功");
            } else {
                return Result.error("批量删除失败");
            }
        } catch (Exception e) {
            logger.error("批量删除评价异常", e);
            return Result.error("系统异常");
        }
    }
    
    /**
     * 获取评价统计信息
     */
    @GetMapping("/stats")
    @ResponseBody
    public Result getReviewStats(@RequestParam(required = false) Long productId, HttpSession session) {
        try {
            Map<String, Object> stats = new HashMap<>();
            
            if (productId != null) {
                // 获取特定商品的评价统计
                stats.put("total", reviewService.getReviewCountByProductId(productId));
                stats.put("averageRating", reviewService.getAverageRatingByProductId(productId));
                stats.put("ratingStats", reviewService.getRatingStatsByProductId(productId));
            } else {
                // 获取全局评价统计
                User currentUser = (User) session.getAttribute("user");
                if (currentUser == null) {
                    return Result.unauthorized("请先登录");
                }
                
                // 简单的权限检查
                if (!"admin".equals(currentUser.getUsername())) {
                    return Result.forbidden("权限不足");
                }
                
                stats.put("total", reviewService.getReviewCount());
            }
            
            return Result.success("查询成功", stats);
        } catch (Exception e) {
            logger.error("获取评价统计信息异常: productId={}", productId, e);
            return Result.error("系统异常");
        }
    }
}